from rest_framework.views import exception_handler
from django.db import DatabaseError
from rest_framework.response import Response
from rest_framework import status
from redis import RedisError

import logging
logger = logging.getLogger('django')

def custom_excetion_handler(exc,context):
    '''
    自定義異常處理
    :param exc: 發生異常時的異常對象
    :param context: 拋出異常的上下文
    :return: Response響應對象
    '''
    #調用drf框架原生的異常處理方法
    response = exception_handler(exc, context)

    if response is None:
        view = context['view']
        if isinstance(exc, DatabaseError) or isinstance(exc, RedisError):
            # 数据库异常
            logger.error('[%s] %s' % (view, exc))
            response = Response({'message': '服务器内部错误'}, status=status.HTTP_507_INSUFFICIENT_STORAGE)

    return response
